package com.tengju.data.domain.shared;

import lombok.Getter;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author chenhang
 * @Date 2021/3/19
 */
@Getter
public class Quarter {

    LocalDate startDate;
    LocalDate endDate;
    Month startMonth;
    Month endMonth;
    String quarterStr;
    LocalDate randomDate;

    public Quarter(LocalDate randomDate) {
        if (randomDate == null) {
            return;
        }
        this.randomDate = randomDate;
        this.startDate = DateUtil.getFirstDateOfQuarter(randomDate);
        startMonth = new Month(startDate);
        endMonth = startMonth.nextMonth().nextMonth();
        this.endDate = endMonth.getEndDate();
        this.quarterStr = DateUtil.getYearQuarterByYearMonth(startMonth.getMonthInt() + "");
    }

    public Quarter(String quarterStr) {
        this(DateUtil.getQuarterMin(quarterStr).toLocalDate());
    }

    public boolean sameQuarter(LocalDate date) {
        return date != null && this.startDate.equals(DateUtil.getFirstDateOfQuarter(date));
    }

    public List<Month> listMonth() {
        return List.of(startMonth,startMonth.nextMonth(),endMonth);
    }

    public List<Month> listMonthUntilDay(LocalDate day) {
        Month stopMonth = new Month(day);
        if (stopMonth.equals(startMonth)) {
            return List.of(startMonth);
        }
        if (stopMonth.equals(startMonth.nextMonth())) {
            return List.of(startMonth,startMonth.nextMonth());
        }
        if (stopMonth.equals(endMonth)) {
            return listMonth();
        }
        return Collections.emptyList();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Quarter quarter = (Quarter) o;
        return quarterStr.equals(quarter.quarterStr);
    }

    @Override
    public int hashCode() {
        return Objects.hash(quarterStr);
    }
}
